package view.code
{
	import com.adobe.cairngorm.control.CairngormEventDispatcher;

	import component.renderers.RendererDataBar;
	import component.renderers.RendererIconLabel;
	import component.renderers.RendererLabel;

	import define.Localization;

	import flash.geom.Point;

	import mvc.command.client.IArmoryTipClient;
	import mvc.control.ArmoryEvent;

	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.controls.AdvancedDataGrid;
	import mx.controls.Image;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridColumnGroup;
	import mx.core.ClassFactory;
	import mx.core.UIComponent;
	import mx.events.AdvancedDataGridEvent;
	import mx.events.DragEvent;
	import mx.events.FlexEvent;
	import mx.events.ListEvent;
	import mx.events.ToolTipEvent;
	import mx.managers.DragManager;
	import mx.managers.ToolTipManager;

	import orm.fantasy.TblItemPropertyVO;
	import orm.fantasy.TblItemVO;

	import view.design.DesignArmoryTip;

	import vo.ArmoryBean;

	public class CodeSelector extends HBox
	{
		public var dgSelector:AdvancedDataGrid;

		public function CodeSelector()
		{
			_l = Localization.instance;
		}

		private var _l:Localization;

		public function showOptional(tblItemList:ArrayCollection):void
		{
			// 补完数据，生成 dataProvider
			var dgDataProvider:ArrayCollection = new ArrayCollection();
			for each(var tblItemVO:TblItemVO in tblItemList)
			{
				var bean:ArmoryBean = new ArmoryBean();
				bean.itemVo = tblItemVO;
				var index:int = dgDataProvider.length;
				for(var i:int = 0; i < dgDataProvider.length; i++)
				{
					var dpItem:ArmoryBean = dgDataProvider.getItemAt(i) as ArmoryBean;
					if(int(dpItem.itemPropertyVo.info_item_level) > int(bean.itemPropertyVo.info_item_level))
					{
						index = i;
						break;
					}
					else
						continue;
				}
				dgDataProvider.addItemAt(bean, index);
			}
			// 创建 Column
			var groupedColumns:Array = [];
			// Information
			groupedColumns.push(getColumnGroup(_l.s("information"), getInfoCols()));
			// 属性
//			getPropCols(dgDataProvider);
			groupedColumns.push(getColumnGroup(_l.s("properties"), getPropCols(dgDataProvider)));
			// ok
			dgSelector.groupedColumns = groupedColumns;
			dgSelector.dataProvider = dgDataProvider;
//			dgSelector.addEventListener(FlexEvent.UPDATE_COMPLETE, dgSelector_updateCompleteHandler);
		}

		private function getInfoCols():Array
		{
			var result:Array = [];
			result.push(
				getColumn(_l.s("item_name"), "itemPropertyVo.info_item_name", 240, RendererIconLabel, "items", "itemPropertyVo.info_icon"));
			result.push(
				getColumn(_l.s("armory_slot"), "itemVo.slot", 60, RendererLabel));
			result.push(
				getColumn(_l.s("armory_type"), "itemVo.type", 60, RendererLabel));
			result.push(
				getColumn(_l.s("i_lvl"), "itemPropertyVo.info_item_level", 70, RendererLabel));
			result.push(
				getColumn(_l.s("acquisition"), "itemDescription.acquisition", 280, RendererIconLabel, "side", "itemPropertyVo.info_side"));
//			result.push(
//				getColumn(_l.s("bind"), "itemPropertyVo.info_bind_type", 60, RendererLabel));
//			result.push(
//				getColumn(_l.s("unique"), "itemPropertyVo.info_unique_type", 60, RendererLabel));
			return result;
		}

		private function analyse(host:Object, propName:String, dataAnalyser:Object):void
		{
			var value:int = int(host[propName]);
			if(dataAnalyser[propName] == null)
			{
				if(value == 0)
					return;
				else
					dataAnalyser[propName] = {total: 0, count: 0, min: 0, max: 0};
			}

			dataAnalyser[propName].total = dataAnalyser[propName].total + value;
			dataAnalyser[propName].count = dataAnalyser[propName].count + 1;
			dataAnalyser[propName].min = Math.min(dataAnalyser[propName].min, value);
			dataAnalyser[propName].max = Math.max(dataAnalyser[propName].max, value);
		}

		private function getPropCols(dgDataProvider:ArrayCollection):Array
		{
			var dataAnalyser:Object = {};
			for each(var aBean:ArmoryBean in dgDataProvider)
			{
				var itemPropertyVo:TblItemPropertyVO = aBean.itemPropertyVo;
				var itemVo:TblItemVO = aBean.itemVo;

				for each(var analyseKey:String in analyseKeys)
				{
					analyse(itemPropertyVo, analyseKey, dataAnalyser);
				}
			}

			var result:Array = [];

			for each(var key:String in analyseKeys)
			{
				if(dataAnalyser[key] != null)
					result.push(getColumn(_l.s(key + "_short"), "itemPropertyVo." + key + "?max=" + dataAnalyser[key].max, 50, RendererDataBar));
			}
			return result;
		}

		private function get analyseKeys():Array
		{
			var result:Array = [];
			result.push("base_strenth");
			result.push("base_agility");
			result.push("base_intellect");
			result.push("base_spirit");
			result.push("base_stamina");

			result.push("general_crit_rating");
			result.push("general_hit_rating");
			result.push("general_haste_rating");

			result.push("physical_attack_power");
			result.push("physical_armor_penetration");
			result.push("physical_expertise_rating");

			result.push("spell_power");
			result.push("spell_penetration");
			result.push("spell_mana_regen");

			result.push("defense_defense_rating");
			result.push("defense_block_rating");
			result.push("defense_block_value");
			result.push("defense_dodge_rating");
			result.push("defense_parry_rating");
			result.push("defense_resilience");
			result.push("defense_health_regen");

			return result;
		}

		private function getColumn(headerText:String, dataFields:String, width:int, renderer:Class,
			iconDir:String = null, iconDataFields:String = null):AdvancedDataGridColumn
		{
			var factory:ClassFactory = new ClassFactory(renderer);
			if(renderer == RendererLabel || renderer == RendererDataBar)
				factory.properties = {dataFields: dataFields};
			else if(renderer == RendererIconLabel)
				factory.properties = {iconDir: iconDir, iconDataFields: iconDataFields, labelDataFields: dataFields};

			var column:AdvancedDataGridColumn = new AdvancedDataGridColumn();
			column.headerText = headerText;
			column.dataField = dataFields;
			column.width = width;
			column.sortCompareFunction = dgSelector_sortCompareFunction;
			column.setStyle("textAlign", "center");
			//column.sortDescending = true;
			column.itemRenderer = factory;

			return column;
		}

		private function getColumnGroup(headerText:String, columns:Array):AdvancedDataGridColumnGroup
		{
			var group:AdvancedDataGridColumnGroup = new AdvancedDataGridColumnGroup();
			group.headerText = headerText;
			group.children = columns;

			return group;
		}
		private var _selectedDataFields:Array;

		protected function dgSelector_headerReleaseHandler(event:AdvancedDataGridEvent):void
		{
			if(event.dataField != null)
				_selectedDataFields = event.dataField.split(".");
		}

//		private function dgSelector_updateCompleteHandler(event:FlexEvent):void
//		{
//			dgSelector.removeEventListener(FlexEvent.UPDATE_COMPLETE, dgSelector_updateCompleteHandler);
//			dgSelector.dispatchEvent(new AdvancedDataGridEvent(
//				AdvancedDataGridEvent.HEADER_RELEASE, false, false, 1, "itemPropertyVo.info_item_level"));
//		}

		private function dgSelector_sortCompareFunction(o1:Object, o2:Object):int
		{
			var temp:Object;
			var field:String;

			temp = o1;
			for each(field in _selectedDataFields)
			{
				field = field.split("?")[0];
				temp = temp[field];
			}
			var s1:String = temp.toString();

			temp = o2;
			for each(field in _selectedDataFields)
			{
				field = field.split("?")[0];
				temp = temp[field];
			}
			var s2:String = temp.toString();

			var r:int;
			if(isNaN(Number(s1)) || isNaN(Number(s2)))
				r = s1.localeCompare(s2);
			else
				r = Number(s1) - Number(s2);
			if(r != 0)
				r = r / Math.abs(r);
			return r;
		}

		protected function tabCharacters_dragCompleteHandler(event:DragEvent):void
		{
			if(event.action == DragManager.COPY)
			{
				var armoryBean:ArmoryBean = (event.dragSource.dataForFormat(event.dragSource.formats[0]) as Array)[0] as ArmoryBean;
				var mvcEvent:ArmoryEvent = new ArmoryEvent(ArmoryEvent.EQUIP_ONE_SLOT);
				mvcEvent.data = {armoryBean: armoryBean};
				CairngormEventDispatcher.getInstance().dispatchEvent(mvcEvent);
			}
		}
	}
}